<template>
	<view class="edit-advance-page">
		<!-- 自定義導航欄 -->
		<u-navbar
			title="编辑"
			:border="false"
			:auto-back="true"
			:bg-color="'#FFFFFF'"
			:title-color="'#333333'"
			:title-size="36"
			:title-weight="'bold'"
			placeholder
		>
			<template #right>
				<u-icon name="more-dot-fill" size="20" color="#333" @click="showMoreOptions"></u-icon>
				<u-icon name="search" size="20" color="#333" @click="showSearch" style="margin-left: 20rpx;"></u-icon>
			</template>
		</u-navbar>

		<!-- 表單內容 -->
		<view class="form-content">
			<!-- 事由 -->
			<view class="form-section">
				<view class="section-header">
					<text class="section-title">事由事由</text>
				</view>
				<input 
					v-model="formData.reason"
					placeholder="请输入事由"
					class="form-input"
				/>
			</view>

			<!-- 借款明细 -->
			<view class="form-section">
				<view class="section-header">
					<text class="section-title">借款明细</text>
				</view>
				<view 
					v-for="(item, index) in formData.loanDetails" 
					:key="index"
					class="loan-detail-item"
				>
					<view class="detail-header">
						<text class="detail-number">({{ index + 1 }}) 借款明细</text>
						<view class="detail-actions">
							<button 
								class="btn btn-primary"
								@click="copyDetail(index)"
							>
								复制
							</button>
							<button 
								class="btn btn-error"
								@click="deleteDetail(index)"
							>
								删除
							</button>
						</view>
					</view>
					
					<!-- 费用项目 -->
					<view class="form-field">
						<text class="field-label required">*费用项目</text>
						<view 
							class="select-field"
							@click="selectExpenseItem(index)"
						>
							<text class="select-text">{{ item.expenseItem || '请选择>' }}</text>
							<text class="select-arrow">›</text>
						</view>
					</view>
					
					<!-- 借款金额 -->
					<view class="form-field">
						<text class="field-label required">*借款金额</text>
						<input 
							v-model="item.loanAmount"
							placeholder="请输入借款金额"
							type="number"
							class="amount-input"
						/>
					</view>
				</view>
				
				<!-- 添加按钮 -->
				<button 
					class="add-button"
					@click="addLoanDetail"
				>
					<text class="add-icon">+</text>
					<text class="add-text">添加借款明细</text>
				</button>
			</view>

			<!-- 附件上传 -->
			<view class="form-section">
				<view class="section-header">
					<text class="section-title">附件上传</text>
				</view>
				<view class="upload-area">
					<view 
						v-for="(file, index) in formData.attachments" 
						:key="index"
						class="file-item"
					>
						<!-- 图片缩略图 -->
						<image 
							v-if="isImageFile(file.name)" 
							:src="getImageUrl(file)" 
							class="file-thumbnail"
							mode="aspectFill"
							@click="previewImage(file)"
						/>
						<!-- 文件图标 -->
						<view v-else class="file-icon" @click="previewFile(file)">
							<text class="icon-text">📎</text>
						</view>
						<!-- 文件信息 -->
						<view class="file-info">
							<text class="file-name">{{ file.name }}</text>
							<text class="file-size" v-if="file.fileSize">{{ formatFileSize(file.fileSize) }}</text>
						</view>
						<!-- 删除按钮 -->
						<text class="delete-file" @click.stop="deleteFile(index)">×</text>
					</view>
					<view class="upload-placeholder" @click="chooseFile">
						<text class="upload-icon">📎</text>
						<text class="upload-text">点击上传附件</text>
					</view>
				</view>
			</view>

			<!-- 提交按钮 -->
			<button class="submit-button" @click="submitForm">
				保存修改
			</button>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'

// API基础URL常量
const API_BASE_URL = 'https://hongjiang.hj-hr.com'

// 表單數據
const formData = reactive({
	reason: '事由事由',
	loanDetails: [
		{
			expenseItem: '预付员工工资',
			loanAmount: '111'
		},
		{
			expenseItem: '',
			loanAmount: ''
		}
	],
	attachments: []
})

// 方法
const showMoreOptions = () => {
	uni.showActionSheet({
		itemList: ['保存草稿', '预览', '设置'],
		success: (res) => {
			console.log('选择了:', res.tapIndex)
		}
	})
}

const showSearch = () => {
	uni.showToast({
		title: '搜索功能',
		icon: 'none'
	})
}

const selectExpenseItem = (index: number) => {
	uni.navigateTo({
		url: `/pages/advance/filter?type=expense&index=${index}`
	})
}

const addLoanDetail = () => {
	formData.loanDetails.push({
		expenseItem: '',
		loanAmount: ''
	})
}

const copyDetail = (index: number) => {
	const detail = formData.loanDetails[index]
	formData.loanDetails.push({
		expenseItem: detail.expenseItem,
		loanAmount: detail.loanAmount
	})
	uni.showToast({
		title: '复制成功',
		icon: 'success'
	})
}

const deleteDetail = (index: number) => {
	if (formData.loanDetails.length <= 1) {
		uni.showToast({
			title: '至少保留一条借款明细',
			icon: 'none'
		})
		return
	}
	
	uni.showModal({
		title: '确认删除',
		content: '确定要删除这条借款明细吗？',
		success: (res) => {
			if (res.confirm) {
				formData.loanDetails.splice(index, 1)
				uni.showToast({
					title: '删除成功',
					icon: 'success'
				})
			}
		}
	})
}

const afterRead = (event: any) => {
	const { file } = event.detail
	formData.attachments.push(file)
	uni.showToast({
		title: `已选择${file.name}`,
		icon: 'success'
	})
}

// 判断是否为图片文件
const isImageFile = (fileName: string) => {
	if (!fileName) return false
	const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']
	const lowerFileName = fileName.toLowerCase()
	return imageExtensions.some(ext => lowerFileName.endsWith(ext))
}

// 获取图片URL
const getImageUrl = (file: any) => {
	// 优先使用缩略图，如果没有则使用原图
	let imageUrl = file.thumbUrl || file.url || ''
	
	// 如果URL是相对路径，添加基础URL前缀
	if (imageUrl && !imageUrl.startsWith('http')) {
		imageUrl = API_BASE_URL + imageUrl
	}
	
	return imageUrl
}

// 格式化文件大小
const formatFileSize = (bytes: number) => {
	if (bytes === 0) return '0 B'
	const k = 1024
	const sizes = ['B', 'KB', 'MB', 'GB']
	const i = Math.floor(Math.log(bytes) / Math.log(k))
	return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 预览图片
const previewImage = (file: any) => {
	if (!isImageFile(file.name)) {
		uni.showToast({
			title: '该文件不是图片，无法预览',
			icon: 'none'
		})
		return
	}
	
	const imageUrl = getImageUrl(file)
	if (!imageUrl) {
		uni.showToast({
			title: '图片地址无效',
			icon: 'none'
		})
		return
	}
	
	console.log('预览图片URL:', imageUrl)
	
	// 使用uni-app的图片预览功能
	uni.previewImage({
		current: imageUrl,
		urls: [imageUrl],
		success: () => {
			console.log('图片预览成功')
		},
		fail: (error) => {
			console.error('图片预览失败:', error)
			uni.showToast({
				title: '图片预览失败',
				icon: 'none'
			})
		}
	})
}

// 预览文件
const previewFile = (file: any) => {
	uni.showToast({
		title: '该文件类型不支持预览',
		icon: 'none'
	})
}

const deleteFile = (index: number) => {
	formData.attachments.splice(index, 1)
}

const validateForm = () => {
	if (!formData.reason.trim()) {
		uni.showToast({
			title: '请输入事由',
			icon: 'none'
		})
		return false
	}
	
	for (let i = 0; i < formData.loanDetails.length; i++) {
		const detail = formData.loanDetails[i]
		if (!detail.expenseItem) {
			uni.showToast({
				title: `请选择第${i + 1}条的费用项目`,
				icon: 'none'
			})
			return false
		}
		if (!detail.loanAmount) {
			uni.showToast({
				title: `请输入第${i + 1}条的借款金额`,
				icon: 'none'
			})
			return false
		}
	}
	
	return true
}

const submitForm = () => {
	if (!validateForm()) {
		return
	}
	
	uni.showToast({
		title: '保存成功',
		icon: 'success'
	})
	
	// 延遲返回上一頁
	setTimeout(() => {
		uni.navigateBack()
	}, 1000)
}

const chooseFile = () => {
	uni.chooseFile({
		count: 9,
		type: 'file',
		success: (res) => {
			const file = res.tempFiles[0]
			formData.attachments.push(file)
			uni.showToast({
				title: `已选择${file.name}`,
				icon: 'success'
			})
		}
	})
}

onMounted(() => {
	console.log('编辑预支页面加载完成')
	// 这里可以根据传入的ID加载预支数据
})
</script>

<style lang="scss" scoped>
.edit-advance-page {
	background-color: #F5F5F5;
	min-height: 100vh;
	padding-bottom: 120rpx;
}

/* 表单内容 */
.form-content {
	padding: 20rpx;
	padding-top: 120rpx; /* Adjust padding-top to account for navbar height */
}

.form-section {
	background-color: #FFFFFF;
	border-radius: 12rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
	
	.section-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 20rpx;
	}
	
	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
	}
	
	.form-input, .amount-input {
		background-color: #F5F5F5;
		border-radius: 8rpx;
		padding: 20rpx;
		font-size: 28rpx;
		color: #333;
		border: none;
	}
	
	.select-field {
		display: flex;
		align-items: center;
		background-color: #F5F5F5;
		border-radius: 8rpx;
		padding: 20rpx;
		font-size: 28rpx;
		color: #333;
	}
	
	.select-text {
		flex: 1;
	}
	
	.select-arrow {
		font-size: 28rpx;
		color: #999;
		margin-left: 10rpx;
	}
	
	.form-field {
		margin-bottom: 20rpx;
		
		&:last-child {
			margin-bottom: 0;
		}
		
		.field-label {
			display: block;
			font-size: 28rpx;
			color: #333333;
			margin-bottom: 15rpx;
			
			&.required::before {
				content: '*';
				color: #FF4757;
				margin-right: 5rpx;
			}
		}
	}
}

/* 借款明细 */
.loan-detail-item {
	background-color: #F8F8F8;
	border-radius: 12rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
	
	.detail-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 20rpx;
	}
	
	.detail-number {
		font-size: 28rpx;
		color: #333333;
		font-weight: 500;
	}
	
	.detail-actions {
		display: flex;
		gap: 10rpx;
	}
	
	.btn {
		padding: 8rpx 16rpx;
		font-size: 26rpx;
		border-radius: 8rpx;
	}
	
	.btn-primary {
		background-color: #FF6B35;
		border-color: #FF6B35;
		color: #FFFFFF;
	}
	
	.btn-error {
		background-color: #FF4757;
		border-color: #FF4757;
		color: #FFFFFF;
	}
}

/* 附件上传 */
.upload-area {
	padding: 20rpx;
	background-color: #F5F5F5;
	border-radius: 12rpx;
}

.file-item {
	display: flex;
	align-items: center;
	padding: 15rpx;
	background-color: #FFFFFF;
	border-radius: 8rpx;
	border: 1rpx solid #E0E0E0;
	margin-bottom: 15rpx;
	transition: all 0.2s ease;
	
	&:hover {
		background-color: #F8F8F8;
		border-color: var(--u-primary);
	}
}

.file-thumbnail {
	width: 60rpx;
	height: 60rpx;
	border-radius: 6rpx;
	margin-right: 15rpx;
	flex-shrink: 0;
	cursor: pointer;
}

.file-icon {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #E0E0E0;
	border-radius: 6rpx;
	margin-right: 15rpx;
	flex-shrink: 0;
	cursor: pointer;
}

.icon-text {
	font-size: 32rpx;
	color: #666666;
}

.file-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 5rpx;
}

.file-name {
	font-size: 28rpx;
	color: #333333;
	font-weight: 500;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.file-size {
	font-size: 24rpx;
	color: #999999;
}

.file-name {
	flex: 1;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.delete-file {
	font-size: 36rpx;
	color: #FF4757;
	margin-left: 10rpx;
}

.upload-placeholder {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	background-color: #FF6B35;
	border-radius: 8rpx;
	padding: 20rpx;
	color: #FFFFFF;
	font-size: 28rpx;
}

.upload-icon {
	font-size: 40rpx;
	margin-bottom: 10rpx;
}

.upload-text {
	font-size: 28rpx;
}

/* 提交按钮 */
.submit-button {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	padding: 30rpx;
	background-color: #FF6B35;
	color: #FFFFFF;
	font-size: 32rpx;
	border-radius: 8rpx;
	border: none;
	width: 100%;
}
</style>
